package com.linkage.seapeak.activity.project;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.ZQUserDetailActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.ZQUserZQDetailActivity;
import com.linkage.jz.bankruptcy.adapter.SearchDeclarationListAdapter;
import com.linkage.jz.bankruptcy.base.BaseCreateActivity;
import com.linkage.jz.bankruptcy.bean.SearchDeclarationBean;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.seapeak.recyclebundle.AYSwipeRecyclerView;
import com.seapeak.recyclebundle.BaseRecyclerAdapter;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 搜索申报信息
 */
public class SearchDeclarationInfoActivity extends BaseCreateActivity implements AYSwipeRecyclerView.OnRefreshLoadListener {

    private EditText                     mEditSearchContent;
    private AYSwipeRecyclerView          mRecyclerView;
    private SearchDeclarationListAdapter mAdapter;

    private List<SearchDeclarationBean> mList = new ArrayList();

    private int pageNo   = 1;
    private int pageSize = 20;

    private String mProjectId;
    private String mCreditorName;

    @Override
    protected void onCreate( Bundle savedInstanceState ) {
        setContentView(R.layout.activity_declaration_search);

        super.onCreate(savedInstanceState);

    }

    @Override
    public void initTitle() {
        titlebar_title.setText("申报信息查找");
    }

    @Override
    public void initView() {
        mEditSearchContent = findViewById(R.id.edit_search_content);
        mRecyclerView = findViewById(R.id.recyclerView);
        mRecyclerView.setOnRefreshLoadLister(this);
        mRecyclerView.setMode(AYSwipeRecyclerView.SwipeType.ONLY_START);

        mAdapter = new SearchDeclarationListAdapter(this, mList);
        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick( View v, int position, RecyclerView.ViewHolder viewHolder ) {
                SearchDeclarationBean temp = mList.get(position);
                Intent intent = new Intent(SearchDeclarationInfoActivity.this, ZQUserDetailActivity.class);
                intent.putExtra("creditorId", temp.getCreditorId());
                if (temp.getCreditorRightsId() != null) {
                    intent.putExtra("creditorRightsId", temp.getCreditorRightsId());
                } else {
                    intent.putExtra("creditorRightsId", "");
                }
                intent.putExtra("proid", temp.getProjectId());
                intent.putExtra("page",1);
                startActivity(intent);
            }
        });
        mRecyclerView.setAdapter(mAdapter);

        mEditSearchContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction( TextView v, int actionId, KeyEvent event ) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    mCreditorName = mEditSearchContent.getText().toString().trim();
                    if (!TextUtils.isEmpty(mCreditorName)) {
                        mRecyclerView.startLoadFirst();
                    }
                    return true;
                } else {
                    return false;
                }
            }
        });
    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            mProjectId = intent.getStringExtra("projectId");
            loadFirst();
        }
    }

    @Override
    public void setListener() {

    }

    @Override
    public void loadFirst() {
        pageNo = 1;
        loadPageData(true);
    }

    @Override
    public void loadNext() {
        loadPageData(false);
    }

    private void loadPageData( final boolean isFirstMode ) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            getToken();
            return;
        }

        if (TextUtils.isEmpty(mProjectId) || TextUtils.isEmpty(mCreditorName))
            mCreditorName = "";

        Network.getAPIService()
                .searchDeclarationData(getUserToken(), mProjectId, mCreditorName, pageNo, pageSize)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext( JsonObject json ) {

                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onError(new Throwable(json.get("msg").getAsString()));
                            return;
                        } else {
                            JsonObject                  data  = json.getAsJsonObject("data");
                            JsonArray                   array = data.getAsJsonArray("list");
                            List<SearchDeclarationBean> temp  = new ArrayList<>();
                            for (int i = 0; i < array.size(); i++) {
                                SearchDeclarationBean item = new Gson().fromJson(array.get(i), SearchDeclarationBean.class);
                                temp.add(item);
                            }

                            if (isFirstMode)
                                mList.clear();

                            mList.addAll(temp);
                            int count = data.get("totalCount").getAsInt();
                            mRecyclerView.onFinishRequest(false, pageNo * pageSize < count);
                            pageNo++;
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError( Throwable e ) {
                        super.onError(e);
                    }
                });
    }
}
